package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketStorage;
import com.cskaoyan.market.service.AdminStorageService;
import com.cskaoyan.market.service.AdminStorageServiceImpl;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@WebServlet("/admin/storage/*")
@MultipartConfig
public class AdminStorageCreateController extends HttpServlet {
    AdminStorageService adminStorageService =new AdminStorageServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String op =requestURI.replace(req.getContextPath()+"/admin/storage/","");
        if("create".equals(op)){
            create(req,resp);
        }
    }
    private void create(HttpServletRequest req, HttpServletResponse resp)  {
        Part part = null;
        try {
            part = req.getPart("file");
            String fileName = part.getSubmittedFileName();
            long size = part.getSize();
            String contentType = part.getContentType();
            String key = UUID.randomUUID() + "-" + fileName;

            MarketStorage marketStorage = new MarketStorage();

            marketStorage.setUrl("http://localhost:8083/storage/" + key);
            marketStorage.setSize((int)size);
            marketStorage.setName(fileName);
            marketStorage.setType(contentType);
            marketStorage.setKey(key);
            marketStorage.setDeleted(false);
            marketStorage.setAddTime(LocalDateTime.now());
            //后续修改数据的时候，只需要去修改更新时间即可
            marketStorage.setUpdateTime(LocalDateTime.now());


            String path = "D:/image";
            part.write(path + "/" + key);

            //将这条记录写到数据库
            adminStorageService.create(marketStorage);
            Object ok = ResponseUtil.ok(marketStorage);
            String s = JacksonUtil.getObjectMapper().writeValueAsString(ok);
            resp.getWriter().write(s);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        }

    }
}
